package com.thoughtworks.biblioteca;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

/**
 * Command design pattern. It is the receiver to really perform the command.
 * Read the books to memory from the file and hold them in a HashMap. It also
 * provide a singleton instance of the class to make sure all the command be
 * performed in the same book library.
 */
public class BookLibrary {
    private final static String BOOK_LIBRARY_PATH = "/resource/Books.lib";
    private static BookLibrary bookLibraryInstance = new BookLibrary();

    private HashMap<Integer, Book> bookLibrary;

    private BookLibrary() {
        bookLibrary = new HashMap<Integer, Book>();
        loadBooksFromFile(this.getClass().getResource("/").getPath()
                + BOOK_LIBRARY_PATH);
    }

    /**
     * load books from file to memory.
     */
    private boolean loadBooksFromFile(String bookLibraryFilePath) {
        File booksFile = new File(bookLibraryFilePath);
        BufferedReader reader = null;
        if (booksFile.exists()) {
            try {
                reader = new BufferedReader(new InputStreamReader(
                        new FileInputStream(booksFile)));
                String bookInfo;
                String[] bookInfoArray;
                while ((bookInfo = reader.readLine()) != null
                        && !"".equals(bookInfo)) {
                    bookInfoArray = bookInfo.split(",");
                    bookLibrary.put(Integer.parseInt(bookInfoArray[0].trim()),
                            new Book(bookInfoArray[1].trim(), bookInfoArray[2]
                                    .trim()));
                }
            } catch (FileNotFoundException e) {
                System.out
                        .println("Don't find the book library file: Books.lib.");
                return false;
            } catch (IOException e) {
                System.out.println("Something wrong with the IO.");
                return false;
            } finally {
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    System.out.println("Something wrong with the IO.");
                    return false;
                }
            }
            return true;
        } else {
            System.out.println("Don't find the book library file: Books.lib.");
            return false;
        }
    }

    /**
     * list books catalog to screen
     * @return boolean
     */
    public boolean listBookCatalogToScreen() {
        for (Integer bookNumber : bookLibrary.keySet()) {
            String bookInfo = String.format("%1$s. %2$s by %3$s", bookNumber,
                    bookLibrary.get(bookNumber).getBookName(), bookLibrary.get(
                    bookNumber).getAuthorName());
            System.out.println(bookInfo);
        }
        return true;
    }


    /**
     * check out a specific book by the selection of the user.
     * @param bookNumber
     * @return bookNumber, if the book doesn't exist, return null
     */
    public Integer checkOutBook(Integer bookNumber) {
        if (bookLibrary.containsKey(bookNumber)) {
            System.out.println("\n Thank You! Enjoy the book.");
            return bookNumber;
        } else {
            System.out.println("\nSorry we don't have that book yet.");
            return null;
        }

    }

    /**
     * check the book library number.
     */
    public void checkBookLibraryNumber() {
        System.out.println("\nPlease talk to Librarian. Thank you.");
    }

    /**
     * return a singleton instance of the class
     * @return an singleton instance of BookLibrary
     */
    public static BookLibrary getInstance() {
        return bookLibraryInstance;
    }

}
